//
//  XFNetworkTool.swift
//  mxfweibo
//
//  Created by apple1 on 15/12/17.
//  Copyright © 2015年 莫祥富. All rights reserved.
//

import UIKit

import AFNetworking


class XFNetworkTool: AFHTTPSessionManager {


    static let sharedInstance : XFNetworkTool = XFNetworkTool()
    
    private init(){
        let baseURL = NSURL(string:"https://api.weibo.com/")!
        
        super.init(baseURL: baseURL, sessionConfiguration: nil)
        
        self.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //MARK: - 授权相关
//    
    private let client_id = "3591117357"
//    private let client_id = "1903582841"
    
    let redirect_uri = "http://www.baidu.com/"
    
    private let client_secret = "880323a94679cdd12c63f35e71c288e7"
    
//    private let client_secret = "07b7208a7d7b23dc856f5148c9df0469"
    
    //拼接登录界url地址
    func oAuthURL() ->NSURL {
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        return NSURL(string: urlStr)!
    }

    //MARK: －加载AccessToken
    func loadAccessToken(code:String,finished:(result:[String:AnyObject]?,error:NSError?) ->()){
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let parameters = [
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirect_uri
        ]
        
        POST(urlString, parameters: parameters, success: { (_, result) -> Void in
            
            let dict  = result as? [String :AnyObject]
            
            finished(result: dict, error: nil)
            
            }) { (_, error) -> Void in
                
                finished(result: nil, error: error)
        }
        
    }
    
    //MARK: - 加载用户信息
    func loadUserInfo(finished:(result:[String:AnyObject]?,error : NSError?) ->()){
        
        //守卫：没有值的时候就会调用该方法
        guard let access_token = XFUserAccount.loadUserAccount()?.access_token else {
            print("access_token没有值")
            return
        }
        guard let uid = XFUserAccount.loadUserAccount()?.uid else {
            print("uid没有值")
            return
        }
        
        let urlString = "2/users/show.json"
        let parameters = [
            "access_token": access_token,
            "uid": uid
        ]
        
        GET(urlString, parameters: parameters, success: { (_, result) -> Void in
//            print("获取到用户数据:\(result)")
            
            let dict = result as? [String:AnyObject]
            finished(result: dict, error: nil)
            }) { (_, error) -> Void in
                finished(result: nil, error: error)
        }

    }
    
    func loadStatus(finished:(result:[String : AnyObject]?,error : NSError?) -> ()){
    
        guard let access_token = XFUserAccount.loadUserAccount()?.access_token else {
            print("access_token没有值")
            return
        }
        
        let urlString = "2/statuses/home_timeline.json"
        
        let parameters = ["access_token": access_token]
        
        let debug = false
        
        if debug {
            
            loadLocalStatus(finished)
        }
        else {
            
            GET(urlString, parameters: parameters, success: { (_, result) -> Void in
                
                let dict = result as? [String : AnyObject]
                finished(result: dict, error: nil)
                
                }) { (_, error) -> Void in
                    finished(result: nil, error: error)
            }
        }
        

    }
    
    
    func loadLocalStatus(finished:(result:[String : AnyObject]?,error : NSError?) -> ()) {
        
        let path = NSBundle.mainBundle().pathForResource("statuses", ofType: "json")!
        
        let data = NSData(contentsOfFile: path)!
        
        let json = try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0))
        let dict = json as? [String: AnyObject]
        finished(result: dict, error: nil)
    }
 
}
